package com.gs.m_my_goods.model

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.google.gson.Gson
import com.gs.common.API
import com.gs.common.callback.HttpCallback
import com.gs.common.callback.impl.CommonHttpCallback
import com.gs.common.constant.HttpCode
import com.gs.common.constant.StateCode
import com.gs.common.data.Good
import com.gs.common.global.GlobalVariables
import com.gs.m_my_goods.constant.UploadPictureErrorCode
import okhttp3.Call
import okhttp3.Response
import org.json.JSONObject
import java.net.ConnectException
import java.net.SocketTimeoutException

class AddOrUpdateModel(context: Context) {

    private val api by lazy { API.getInstance() }

    fun uploadPicture(picture: Bitmap, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.uploadGoodPicture(picture, object : HttpCallback {
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                val msg = resultJSON["msg"]
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    Log.d("msg", msg.toString())
                    val msgJSON = JSONObject(msg.toString())
                    GlobalVariables.addGoodImgPath = msgJSON["path"].toString()
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                when(msg.toString()) {
                    "文件大小不能超过1MB" -> block.invoke(UploadPictureErrorCode.PICTURE_EXCEED_SIZE_ERROR)
                    "文件名为空，不能正常获取文件类型" -> block.invoke(UploadPictureErrorCode.PICTURE_NULL_POINTER_ERROR)
                    else -> block.invoke(StateCode.STATE_FAILED)
                }
            }

            override fun onError(call: Call, e: Exception) {
                when (e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }

                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }

                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }

    fun addOrUpdateGood(
        state: String,
        username: String,
        goodId: Int?,
        goodTitle: String,
        goodDetailTitle: String,
        goodPicturePath: String,
        goodPrice: Double,
        goodCount: Int,
        block: (Int) -> Unit
    ) {
        block.invoke(StateCode.STATE_LOADING)
        api.addOrUpdateGood(
            state,
            username,
            goodId,
            goodTitle,
            goodDetailTitle,
            goodPicturePath,
            goodPrice,
            goodCount,
            CommonHttpCallback(block)
        )
    }

    fun getGoodsById(goodId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.getGoodsById(goodId, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                val msg = resultJSON["msg"]
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    val msgJSON = JSONObject(msg.toString())
                    val good = Gson().fromJson(msgJSON["goods"].toString(), Good::class.java)
                    Log.d("good", good.toString())
                    GlobalVariables.updateGood = good
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when (e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }

                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }

                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }


    companion object {
        private var instance: AddOrUpdateModel? = null
        fun getInstance(context: Context): AddOrUpdateModel {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = AddOrUpdateModel(context)
                    }
                }
            }
            return instance!!
        }
    }
}